

import { defineStore } from "pinia";

import { store } from "../index";

// 指定menus的类型
interface AdminStore {
    menus:MenusType[];
}


export const useAdminStore = defineStore("admin",{
    state():AdminStore{      //menus作为函数返回值，指定类型
        return{
            menus:[],
        };
    },
    actions:{
        updateMenus(menus:MenusType[]){
            this.menus = menus;
        },
    },
    getters:{
        genNewMenus(state){
            // extends 约束 in映射 （循环）
            // type Record<K extends string | number | symbol, T> = { [P in K]: T; }
            const newMenus:Recordable<MenusType> = {};

            state.menus.forEach((menu)=>{
                if(menu.parentId === 0){
                    // newMenus[menu.id] =  menu;
                    newMenus[menu.id]={...menu,
                        children: newMenus[menu.parentId]?.children ?? []}
                }else{
                    newMenus[menu.parentId] ??= {} as MenusType;
                    newMenus[menu.parentId].children ??= [];
                    newMenus[menu.parentId].children.push(menu);
                }
            });
            return newMenus;
        }
    },
});

export const useAdminStoreWithOut = ()=>useAdminStore(store)